import { Work } from "@/api/interface/work";
import { addWorkApi, deleteWorkApi, getWorkDetailApi, getWorkListApi, updateWorkApi } from "@/api/modules/work";
import { RootThunkAction, store } from "@/redux";
import { Action } from "@/redux/interface";
import * as types from "@/redux/mutation-types";
import { Dispatch } from "redux";

export const saveWorkList = (workList: Work[]) => {
	return {
		type: types.SET_WORK_LIST,
		payload: workList
	};
};

export const saveWorkDetail = (work: Work) => {
	return {
		type: types.SET_WORK_DETAIL,
		payload: work
	};
};

export const getWorkList = (pageNum: number = 1, pageSize: number = 10, wrapper?: Partial<Work>) => {
	store.dispatch(getList(pageNum, pageSize, wrapper));
};

export const getWorkDetail = (id: number) => {
	store.dispatch(getDetail(id));
};

export const addWork = (work: Work) => {
	store.dispatch(add(work));
};

export const removeWork = (id: number) => {
	store.dispatch(remove(id));
};

export const updateWork = (work: Partial<Work>) => {
	store.dispatch(update(work));
};

export const getList = (pageNum: number = 1, pageSize: number = 10, wrapper?: Partial<Work>): RootThunkAction => {
	return async (dispatch: Dispatch<Action<Work[]>>) => {
		const res = await getWorkListApi(pageNum, pageSize, wrapper);
		dispatch(saveWorkList(res.data.rows) ?? []);
	};
};

export const getDetail = (id: number): RootThunkAction => {
	return async (dispatch: Dispatch<Action<Work>>) => {
		const res = await getWorkDetailApi(id);
		dispatch(saveWorkDetail(res.data));
	};
};

export const add = (work: Work): RootThunkAction => {
	return async dispatch => {
		const res = await addWorkApi(work);
		if (res.code === 200) dispatch(getList());
	};
};

export const remove = (id: number): RootThunkAction => {
	return async dispatch => {
		const res = await deleteWorkApi(id);
		if (res.code === 200) dispatch(getList());
	};
};

export const update = (work: Partial<Work>): RootThunkAction => {
	return async dispatch => {
		const res = await updateWorkApi(work);
		if (res.code === 200) dispatch(getList());
	};
};
